<?php

namespace App\Models;

use App\Http\Controllers\Resource\XytsController;
use App\Http\Controllers\Resource\YtysController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/*数字资源（新语听书）model*/

class ResourceXyts extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_xyts';



    /*关联活动类型*/
    public function conBigType()
    {
        return $this->hasOne(ResourceType::class, 'id', 'big_type_id');
    }


    /*关联活动类型*/
    public function conType()
    {
        return $this->hasOne(ResourceTypeExternal::class, 'id', 'type_id');
    }


    /**
     * 获取书籍详情
     * @param id  书籍id
     * @param guid  书籍guid  和 书籍id 2选一
     * @param resource_business_id  资源商id
     */
    public function detail($id = null, $guid = null)
    {
        if (empty($id) && empty($guid)) {
            return false;
        }
        $res = $this->select([
            'id',
            'guid',
            'resource_business_id',
            'title',
            'author',
            'isbn',
            'press',
            'pre_time',
            'img',
            'intro',
            'create_time',
            'big_type_id',
            'type_id',
            'browse_num',
            'is_recom'
        ])->with('conBigType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->with('conType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->where(function ($query) use ($id, $guid) {
            if ($id) {
                $query->where('id', $id);
            } else {
                $query->where('guid', $guid);
            }
        })->where('is_del', 1)
            ->first();

        if ($res) {
            $is_exists_chapter = ResourceBusinessName::where('id', $res->resource_business_id)->value('is_exists_chapter');
            $res->is_exists_chapter = $is_exists_chapter == 1 ? true : false; //是否存在章节，有则可以获取
        }
        return $res;
    }


    /**
     * 添加数据到数据库
     * @param $data
     */
    public function addData($data)
    {
        if (empty($data['book_id'])) {
            return false;
        }

        $big_type_id = 2; //固定是有声书类型
        $res = $this->where('data_unique_id', $data['book_id'])->first(); //book_id 区分大小写检索     数据库对应，数据字段 设置为 binary 也可以
        if (empty($res)) {
            //修改
            $res = new self();
            $guid = get_guid();
            $res->guid = $guid;
        }
        $res->book_id = $data['book_id'];
        $res->resource_business_id = 6; //固定3，云图有声
        $res->title = $data['book_name'];
        $res->big_type_id = $big_type_id;
        $res->type_id = $data['type_id'];
        $res->img = str_replace('http:', 'https:', $data['book_img_url']); //替换成https
        $res->link = null;
        $res->isbn = null;
        $res->intro = $data['book_introduction'];
        $res->author = $data['book_author'];
        $res->narrator = $data['book_narrator'];
        $res->chapter_num = $data['book_chapter_num'];
        $res->duration = $data['book_duration'];
        $res->source = $data['book_source'];
        $res->data_unique_id = $data['book_id']; //数据唯一id
        $res->change_time = date('Y-m-d H:i:s'); //数据唯一id
        $res->is_del = 1;
        $res->save();

        //加入到资源总数据库
        $resourceTotalModel = new ResourceTotal();
        $resourceTotalModel->addData($res);

        return $res->id;
    }


    /**
     *删除下架数据
     */
    public function deleteData($book_id)
    {
        $res = $this->where('data_unique_id', $book_id)->where('is_del', 1)->first(); //bid 区分大小写检索     数据库对应，数据字段 设置为 binary 也可以
        if (empty($res)) {
            return true;
        }
        $res->is_del = 2;
        $res->save();

        //删除总数据
        $resourceTotalModel = new ResourceTotal();
        $resourceTotalModel->deleteData($res->guid);

        return $res->id;
    }


    /**
     * 获取图书目录
     * @param guid  资源guid
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getBookCatalogue($guid)
    {
        $key = md5('getYtysBookCatalogue-' . $guid);
        $res = Cache::get($key);
        $res = null;
        if (empty($res)) {
            $book_info = $this->select('book_id')->where('guid', $guid)->where('is_del', 1)->first();
            $book_id = trim($book_info['book_id']);
            if (empty($book_id)) {
                return false;
            }
            $xytsObj = new XytsController();
            $res = $xytsObj->getBookChapter($book_id);
            if ($res) Cache::set($key, $res, 24 * 60 * 60); //缓存一天
        }
        if (empty($res['data'])) {
            return null;
        }
        return $res;
    }

    /**
     * 获取图书阅读跳转地址
     * @param guid  章节id
     */
    public function getXytsChapterAudioSkipAddress($guid)
    {
        $book_id = $this->where('guid', $guid)->where('is_del', 1)->value('book_id');
        if (empty($book_id)) {
            return null;
        }
        $xytsObj = new XytsController();
        $res = $xytsObj->getAudioSkipInfo($book_id);
        return ['link' => $res];
    }
}
